/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.pc9.pswing.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.Icon;
import javax.swing.ImageIcon;
//import org.apache.batik.transcoder.TranscoderInput;
//import org.apache.batik.transcoder.TranscoderOutput;
//import org.apache.batik.transcoder.image.PNGTranscoder;

/**
 *
 * @author paulocanedo
 */
public class LinuxIconFactory extends GenericIconFactory {

    private static List<File> iconFolders = new ArrayList<File>();

    private static List<File> getSystemIconFolders() {
        if (iconFolders.isEmpty()) {
            iconFolders.add(new File("/usr/share/icons"));
            iconFolders.add(new File(SystemUtilsOS.getUserHomeAsFile(), ".icons"));
        }
        return iconFolders;
    }

    public static File locateIconSystemFolder(String themeName) {
        try {
            File iconFile;
            for (File folder : getSystemIconFolders()) {
                iconFile = new File(folder, themeName);

                if (iconFile.exists()) {
                    return iconFile;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static List<File> locateSecondaryIconSystemFolders(File mainIconFolder) throws Exception {
        File config = new File(mainIconFolder, "index.theme");

        FileInputStream stream = null;
        try {
            stream = new FileInputStream(config);
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

            String line;
            while ((line = reader.readLine()) != null) {
                if (line.toLowerCase().startsWith("inherits=")) {
                    line = line.substring("inherits=".length());
                    String[] themes = line.split(",");

                    File[] folders = new File[themes.length];
                    for (int i = 0; i < themes.length; i++) {
                        folders[i] = locateIconSystemFolder(themes[i]);
                    }
                    return Arrays.asList(folders);
                }
            }
        } finally {
            stream.close();
        }
        return null;
    }

    public static Icon getSystemIcon(String category, String name, int size) {
        Icon icon = null;

        String keyName = category + "." + name;
        Icon iconCache = getIconInCache(keyName);
        if (iconCache != null) {
            return iconCache;
        }

        try {
            File iconSystemFolder = locateIconSystemFolder(SystemUtilsOS.getThemeName());
            String fileIconName = String.format("%s/%d/%s", category, size, name);

            icon = getIcon(iconSystemFolder, fileIconName);
            if (icon == null) {
                List<File> parentFolders = locateSecondaryIconSystemFolders(locateIconSystemFolder(SystemUtilsOS.getThemeName()));
                for (File folder : parentFolders) {
                    icon = getIcon(folder, fileIconName);
                    if (icon != null) {
                        return setIconInCache(keyName, icon);
                    } else {
                        List<File> parentFolders_ = locateSecondaryIconSystemFolders(folder);
                        for (File folder_ : parentFolders_) {
                            icon = getIcon(folder_, fileIconName);
                            if (icon != null) {
                                return setIconInCache(keyName, icon);
                            }
                        }
                    }
                }
            } else {
                return setIconInCache(keyName, icon);
            }
        } catch (Exception ex) {
        }
        return GenericIconFactory.getSystemIcon(category, name, size);
    }

    private static Icon getIcon(File parentFolder, String filename) {
        try {
            String[] extensionsSupported = new String[]{".png", ".svg", ".jpg", ".gif"};
            for (String extension : extensionsSupported) {
                File file = new File(parentFolder, filename + extension);
                if (file.exists()) {
                    filename = file.getAbsolutePath();
                    if (filename.toLowerCase().endsWith(".png") || filename.toLowerCase().endsWith(".jpg")
                            || filename.toLowerCase().endsWith(".gif")) {
                        return new ImageIcon(file.toURI().toURL());
                    } else if (filename.toLowerCase().endsWith(".svg")) {
//                        File temp = File.createTempFile("svgtempfile", ".png", new File("/home/paulocanedo/tmp"));
//                        temp.deleteOnExit();
//
//                        PNGTranscoder t = new PNGTranscoder();
//                        TranscoderInput input = new TranscoderInput(new FileInputStream(file));
//                        TranscoderOutput output = new TranscoderOutput(new FileOutputStream(temp));
//
//                        t.transcode(input, output);
//
//                        return new ImageIcon(temp.toURI().toURL());
                    }
                }
            }

        } catch (Throwable ex) {
        }
        return null;
    }
}
